package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.ReverbType;

import common.SimpleDateFormatter;
import common.TextMessage;

public class History {

	private SimpleDateFormatter simpleDateForm;
	private File logFile;
	protected FileWriter fw;
	private static String LOG_FILE_NAME = "log.txt";

	public History() {
		try {
			simpleDateForm = new SimpleDateFormatter();
			logFile = new File(LOG_FILE_NAME);
			if (!logFile.exists()) {
				logFile.createNewFile();
			}
			fw = new FileWriter(logFile.getName(), true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	//load messages from the log
	public String load(int linesToRead) {
		StringBuilder sb = new StringBuilder();
		try {
			FileReader fr = new FileReader(logFile);
			BufferedReader br = new BufferedReader(fr);
			
			
			//inverse history, newest messages first 
			List<String> tmp = new ArrayList<String>();
			String ch;
			do {
				ch = br.readLine();
				tmp.add(ch);
			} while (ch != null);
			int finishedLines=0;
			for (int i = tmp.size() - 1; i >= 0; i--) {
				finishedLines++;
				if(tmp.get(i) != null) sb.insert(0,tmp.get(i) + "\n");
				if(finishedLines == linesToRead)  break;
			}
			br.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return sb.toString();
	}

	//writes a message to the log.txt
	public void writeMessage(TextMessage msg) {
		BufferedWriter bufferedWriter = null;
		try {
			fw = new FileWriter(logFile.getName(), true);
			bufferedWriter = new BufferedWriter(fw);
			String currentTime = simpleDateForm.calcDate(System
					.currentTimeMillis()) + " - ";
			bufferedWriter.write(currentTime + msg.getContent() + "\n");
			bufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
